//
//  StatusListViewModel.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/3/6.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit
import SDWebImage

class StatusListViewModel {
     //定义一个懒加载的属性
     lazy var statusList = [StatusViewModel]()
    //清除数据的方法
    func cleanUp(){
        self.statusList.removeAll()
    }
    func loadStatus(isPullUp:Bool,finished:(isSuccess:Bool)->()) {
        let since_id = isPullUp ? 0 : (statusList.first?.status.id ?? 0)
        
        let max_id = !isPullUp ?  0 : (statusList.last?.status.id ?? 0)
        
        //加载微博数据
        NetworkTools.shardTools.loadNewLoad(cz_since: since_id, max_id:max_id ){ (result) -> () in
          //取值
            guard let array = result?["statuses"] as?[[String:AnyObject]] else{
                print("您的网络不给力")
                finished(isSuccess: false)
                return
            }
            
            //遍历数组，字典转模型
            var arrayM = [StatusViewModel]()
            
            for dict in array {
                
                arrayM.append(StatusViewModel(status: Status.yy_modelWithJSON(dict)!))
            }
          if isPullUp {
                
                self.statusList += arrayM
                
            }else{
                
                self.statusList = arrayM + self.statusList
            }
            //缓存单张图片
           self.cachSingleImage(arrayM, finished: finished)
           //完成之后  成功回调
            finished(isSuccess: true)
        }
    }
    //缓存单张图片完成之后，要更新配图视图的大小，完成回调刷新表格
    //一定要计算图片数据的长度，
    /// 所有的图片框架，下载图像会检查本地缓存，如果本地缓存存在的话，就不会再下载
    private func cachSingleImage(array:[StatusViewModel],finished:(isSuccessed:Bool)->()){
         //利用调度组来监听单张图片缓存成功
        let group = dispatch_group_create()
        var datalength:Int = 0
        //遍历数组
        for viewModel in array{
        
            if viewModel.singleImage?.count != 1{
               continue
            }
            //程序到这肯定是单张图片
            guard  let urlString = viewModel.singleImage![0].thumbnail_pic,
                url = NSURL(string:urlString) else{
               return
            }
            //入组
            dispatch_group_enter(group)
            SDWebImageManager.sharedManager().downloadImageWithURL(url, options: [], progress: nil, completed: { (image, _, _, _, _) -> Void in
                //判断图像是否下载成功 即使本地缓存存在，回调方法同样被调用image要被返回
                if let image = image ,data = UIImagePNGRepresentation(image){
                //   print(NSHomeDirectory())
                    datalength += data.length
                  //  print(data)
                    
                    //更新单张配图的大小对应的尺寸
                   viewModel.updateSingleImageSize()
                }
                //出错
                dispatch_group_leave(group)
            })
            
            
        }
        //监听下载完成
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            print("数据的长度\(datalength / 1024)K")
            
          //单张图片缓存成功，遍历模型，返回模型数组中每一个单张图片的高度
            for viewModel in array{
            
               viewModel.caleRowHeight()
            }
            
            //回到主线程完成回调
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                
                finished(isSuccessed: true)
                
            })
            
        }
        
        
        
    
    }


}
